package com.dykj.fireFighting.server.base.maintenance.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dykj.fireFighting.api.base.devHisResult.vo.ResultVo;
import com.dykj.fireFighting.api.base.enterprise.entity.Enterprise;
import com.dykj.fireFighting.api.base.enterprise.service.IEnterpriseService;
import com.dykj.fireFighting.api.base.maintenance.dto.MaintenanceStatisticsDto;
import com.dykj.fireFighting.api.base.maintenance.dto.UrgentMaintenanceDto;
import com.dykj.fireFighting.api.base.maintenance.entity.UrgentMaintenance;
import com.dykj.fireFighting.api.base.maintenance.service.IUrgentMaintenanceService;
import com.dykj.fireFighting.api.base.maintenance.vo.MaintenanceEvaluationVo;
import com.dykj.fireFighting.api.base.maintenance.vo.MaintenanceStatisticsVo;
import com.dykj.fireFighting.api.base.maintenance.vo.UrgentMaintenanceStatisticsVo;
import com.dykj.fireFighting.api.base.maintenance.vo.UrgentMaintenanceVo;
import com.dykj.fireFighting.common.core.service.impl.BaseServiceImpl;
import com.dykj.fireFighting.common.core.vo.PageVo;
import com.dykj.fireFighting.server.base.maintenance.mapper.UrgentMaintenanceMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 紧急维保记录
 *
 * @Author JacksonTu
 * @Date 2021-07-28 08:38:40
 */
@Slf4j
@DubboService
@Transactional(rollbackFor = Exception.class)
public class UrgentMaintenanceServiceImpl extends BaseServiceImpl<UrgentMaintenanceMapper, UrgentMaintenance> implements IUrgentMaintenanceService {

    @Autowired
    private IEnterpriseService enterpriseService;

    @Override
    public UrgentMaintenanceStatisticsVo getStatistics(String weibaoId) {
        return this.baseMapper.getStatistics(weibaoId);
    }

    @Override
    public PageVo<UrgentMaintenanceVo> queryUrgentMaintenanceList(UrgentMaintenanceDto urgentMaintenanceDto) {

        HashMap<String, Object> params = new HashMap<>(16);
        params.put("status", urgentMaintenanceDto.getStatus());
        params.put("sociologyDept", urgentMaintenanceDto.getSociologyDept());
        params.put("maintenanceDept", urgentMaintenanceDto.getMaintenanceDept());
        params.put("reply", urgentMaintenanceDto.getReply());
        params.put("beginTime", urgentMaintenanceDto.getBeginTime());
        params.put("endTime", urgentMaintenanceDto.getEndTime());
        params.put("deviceName", urgentMaintenanceDto.getDeviceName());

        Page page = new Page();
        // 设置当前页码
        page.setCurrent(urgentMaintenanceDto.getPage());
        // 设置页大小
        page.setSize(urgentMaintenanceDto.getLimit());

        return new PageVo<UrgentMaintenanceVo>(this.baseMapper.queryUrgentMaintenanceList(page, params));
    }

    @Override
    public UrgentMaintenanceVo getInfoById(String id) {
        return this.baseMapper.getInfoById(id);
    }

    @Override
    public PageVo<UrgentMaintenanceVo> queryEvaluationList(UrgentMaintenanceDto urgentMaintenanceDto) {
        HashMap<String, Object> params = new HashMap<>(16);
        params.put("status", urgentMaintenanceDto.getStatus());
        params.put("sociologyDept", urgentMaintenanceDto.getSociologyDept());
        params.put("maintenanceDept", urgentMaintenanceDto.getMaintenanceDept());
        params.put("deviceName", urgentMaintenanceDto.getDeviceName());
        Page page = new Page();
        // 设置当前页码
        page.setCurrent(urgentMaintenanceDto.getPage());
        // 设置页大小
        page.setSize(urgentMaintenanceDto.getLimit());

        return new PageVo<UrgentMaintenanceVo>(this.baseMapper.queryEvaluationList(page, params));
    }

    @Override
    public List<MaintenanceStatisticsVo> getMaintenanceStatistics(MaintenanceStatisticsDto maintenanceStatisticsDto) {
        HashMap<String, Object> params = new HashMap<>(16);
        if (StringUtils.isBlank(maintenanceStatisticsDto.getType())) {
            maintenanceStatisticsDto.setType("year");
        }
        params.put("type", maintenanceStatisticsDto.getType());
        params.put("unitId", maintenanceStatisticsDto.getUnitId());
        params.put("wbId", maintenanceStatisticsDto.getWbId());
        return this.baseMapper.getMaintenanceStatistics(params);
    }

    @Override
    public List<Integer> getMaintenanceTodayStatistic(String wbId) {
        List<Integer> numList = new ArrayList<>();
        HashMap<String, Object> params = new HashMap<>(16);
        params.put("wbId", wbId);
        int unitNum = this.baseMapper.getUnitNumByWbId(params);
        numList.add(unitNum);

        MaintenanceStatisticsDto maintenanceStatisticsDto = new MaintenanceStatisticsDto();
        maintenanceStatisticsDto.setWbId(wbId);
        maintenanceStatisticsDto.setType("day");
        List<MaintenanceStatisticsVo> maintenanceStatisticsVoList = getMaintenanceStatistics(maintenanceStatisticsDto);

        if (!CollectionUtils.isEmpty(maintenanceStatisticsVoList)) {
            for (MaintenanceStatisticsVo maintenanceStatisticsVo : maintenanceStatisticsVoList) {
                numList.add(maintenanceStatisticsVo.getValue());
            }
        }
        return numList;
    }

    @Override
    public MaintenanceStatisticsVo getNotFinishedMaintenanceStatistics(String wbId) {
        HashMap<String, Object> params = new HashMap<>(16);
        params.put("wbId", wbId);
        int totalNumber = this.baseMapper.getNotFinishedMaintenanceStatistics(params);
        params.put("status", "notFinished");
        int notFinishedNum = this.baseMapper.getNotFinishedMaintenanceStatistics(params);
        MaintenanceStatisticsVo maintenanceStatisticsVo = new MaintenanceStatisticsVo();
        maintenanceStatisticsVo.setNotFinishedNum(notFinishedNum);
        maintenanceStatisticsVo.setTotalNumber(totalNumber);
        return maintenanceStatisticsVo;
    }

    @Override
    public PageVo<UrgentMaintenanceVo> queryUrgentList(UrgentMaintenanceDto urgentMaintenanceDto) {
        Map<String, Object> params = new HashMap<>();
        params.put("unitId", urgentMaintenanceDto.getSociologyDept());
        params.put("status", urgentMaintenanceDto.getStatus());
        params.put("reply", urgentMaintenanceDto.getReply());
        Page page = new Page();
        // 设置当前页码
        page.setCurrent(urgentMaintenanceDto.getPage());
        // 设置页大小
        page.setSize(urgentMaintenanceDto.getLimit());
        return new PageVo<UrgentMaintenanceVo>(this.baseMapper.queryUrgentList(page, params));
    }

    @Override
    public UrgentMaintenanceVo getUrgentMaintenanceInfoById(String id) {
        return this.baseMapper.getUrgentMaintenanceInfoById(id);
    }

    /**
     * 获取事件周期内社会单位隐患有效整改率得分
     *
     * @param start
     * @param end
     * @param socUnitId
     * @return
     */
    @Override
    public int getSociologyUrgentSocre(String start, String end, String socUnitId) {

        int total = this.baseMapper.getUrgentNum(start, end, socUnitId);
        int doNum = this.baseMapper.getEffectiveUrgentNum(start, end, socUnitId);
        if (total == 0) {
            return 20;
        }
        double rate = (double) doNum / (double) total;
        if (rate > 0.7) {
            return 20;
        }
        if (rate <= 0.7 && rate > 0.3) {
            return 10;
        }
        return 0;
    }

    @Override
    public BigDecimal queryMaintenanceEvaluationAvg(UrgentMaintenanceDto urgentMaintenanceDto) {
        List<MaintenanceEvaluationVo> maintenanceEvaluationVoList = queryMaintenanceEvaluationList(urgentMaintenanceDto);
        int monthRoutineSumScore = maintenanceEvaluationVoList.stream().mapToInt(x -> ((Integer) x.getMonthRoutineScore())).sum();
        int monthUrgentSumScore = maintenanceEvaluationVoList.stream().mapToInt(x -> ((Integer) x.getMonthUrgentScore())).sum();
        int monthRoutineNum = maintenanceEvaluationVoList.stream().mapToInt(x -> ((Integer) x.getMonthRoutineNum())).sum();
        int monthUrgentNum = maintenanceEvaluationVoList.stream().mapToInt(x -> ((Integer) x.getMonthUrgentNum())).sum();

        //尽量用字符串的形式初始化
        BigDecimal mrss = new BigDecimal(String.valueOf(monthRoutineSumScore));
        BigDecimal muss = new BigDecimal(String.valueOf(monthUrgentSumScore));
        BigDecimal mrnum = new BigDecimal(String.valueOf(monthRoutineNum));
        BigDecimal munum = new BigDecimal(String.valueOf(monthUrgentNum));

        BigDecimal size = new BigDecimal(String.valueOf(maintenanceEvaluationVoList.size()));
        //加法
        BigDecimal score = mrss.add(muss);
        BigDecimal num = (mrnum.add(munum)).multiply(size);
        if (BigDecimal.ZERO.equals(num)) {
            return BigDecimal.ZERO;
        }
        //除法
        return score.divide(num, 4, RoundingMode.HALF_UP);
    }


    public MaintenanceEvaluationVo queryMaintenanceEvaluation(UrgentMaintenanceDto urgentMaintenanceDto) {
        List<MaintenanceEvaluationVo> maintenanceEvaluationVoList = queryMaintenanceEvaluationList(urgentMaintenanceDto);
        int monthRoutineSumScore = maintenanceEvaluationVoList.stream().mapToInt(x -> ((Integer) x.getMonthRoutineScore())).sum();
        int monthUrgentSumScore = maintenanceEvaluationVoList.stream().mapToInt(x -> ((Integer) x.getMonthUrgentScore())).sum();
        int monthRoutineNum = maintenanceEvaluationVoList.stream().mapToInt(x -> ((Integer) x.getMonthRoutineNum())).sum();
        int monthUrgentNum = maintenanceEvaluationVoList.stream().mapToInt(x -> ((Integer) x.getMonthUrgentNum())).sum();

        MaintenanceEvaluationVo maintenanceEvaluationVo = new MaintenanceEvaluationVo();
        maintenanceEvaluationVo.setMonthRoutineScore(monthRoutineSumScore);
        maintenanceEvaluationVo.setMonthUrgentScore(monthUrgentSumScore);
        maintenanceEvaluationVo.setMonthRoutineNum(monthRoutineNum);
        maintenanceEvaluationVo.setMonthUrgentNum(monthUrgentNum);

        //尽量用字符串的形式初始化
        BigDecimal mrss = new BigDecimal(String.valueOf(monthRoutineSumScore));
        BigDecimal muss = new BigDecimal(String.valueOf(monthUrgentSumScore));
        BigDecimal mrnum = new BigDecimal(String.valueOf(monthRoutineNum));
        BigDecimal munum = new BigDecimal(String.valueOf(monthUrgentNum));

        BigDecimal size = new BigDecimal(String.valueOf(maintenanceEvaluationVoList.size()));
        //加法
        BigDecimal score = mrss.add(muss);
        BigDecimal num = (mrnum.add(munum)).multiply(size);
        if (BigDecimal.ZERO.equals(num)) {
            maintenanceEvaluationVo.setMonthAvgScore(BigDecimal.ZERO);
        } else {
            //除法
            maintenanceEvaluationVo.setMonthAvgScore(score.divide(num, 4, RoundingMode.HALF_UP));
        }
        return maintenanceEvaluationVo;
    }

    @Override
    public int getCenterNum(List<String> ids, String beginTime, String endTime) {
        return this.baseMapper.getCenterNum(ids, beginTime, endTime);
    }

    @Override
    public int getUnitNum(String id, String beginTime, String endTime) {
        return this.baseMapper.getUnitNum(id, beginTime, endTime);
    }

    @Override
    public List<MaintenanceEvaluationVo> queryMaintenanceEvaluationAvgList(String unitId, String maintenanceDept, String date) {
        List<MaintenanceEvaluationVo> maintenanceEvaluationVoList = new ArrayList<>();
        List<Enterprise> maintenanceList = new ArrayList<>();
        if (StringUtils.isBlank(maintenanceDept)) {
            List<Enterprise> enterpriseList = enterpriseService.queryUnitSelect(unitId);
            if (CollectionUtils.isEmpty(enterpriseList)) {
                return Collections.emptyList();
            }
            Map<String, Object> params = new HashMap<>();
            params.put("enterpriseList", enterpriseList);
            maintenanceList = enterpriseService.queryMaintenanceListByUnit(params);
        } else {
            Enterprise enterprise = enterpriseService.queryById(maintenanceDept);
            maintenanceList.add(enterprise);
        }
        for (Enterprise enterprise : maintenanceList) {
            UrgentMaintenanceDto urgentMaintenanceDto = new UrgentMaintenanceDto();
            urgentMaintenanceDto.setMaintenanceDept(enterprise.getId().toString());
            urgentMaintenanceDto.setEvaluationTime(date);
            MaintenanceEvaluationVo maintenanceEvaluationVo = queryMaintenanceEvaluation(urgentMaintenanceDto);

            maintenanceEvaluationVo.setMaintenanceId(enterprise.getId().toString());
            maintenanceEvaluationVo.setMaintenanceName(enterprise.getEnterpriseName());
            maintenanceEvaluationVo.setIndustryName(enterprise.getIndustryName());
            maintenanceEvaluationVo.setAreaName(enterprise.getAreaName());
            maintenanceEvaluationVoList.add(maintenanceEvaluationVo);
        }
        //list排序
        Integer[] arr = {1};
        return maintenanceEvaluationVoList.stream().sorted(Comparator.comparing(MaintenanceEvaluationVo::getMonthAvgScore).reversed()).peek(e -> e.setRanking(arr[0]++)).collect(Collectors.toList());
    }

    @Override
    public int updateArriveTime(String id, String arriveTime) {
        return this.baseMapper.updateArriveTime(id, arriveTime);
    }

    @Override
    public List<UrgentMaintenanceVo> queryUrgentMaintenanceEvaluationInfoList(UrgentMaintenanceDto urgentMaintenanceDto) {
        Map<String, Object> params = new HashMap<>();
        params.put("maintenanceDeptId", urgentMaintenanceDto.getMaintenanceDept());
        params.put("evaluationDate", urgentMaintenanceDto.getEvaluationTime());
        return this.baseMapper.queryUrgentMaintenanceEvaluationInfoList(params);
    }

    @Override
    public List<MaintenanceEvaluationVo> queryMaintenanceEvaluationAvgListByUnit(String unitId) {
        List<MaintenanceEvaluationVo> maintenanceEvaluationVoList = new ArrayList<>();
        Map<String, Object> params = new HashMap<>();
        params.put("enterpriseId", unitId);
        List<Enterprise> maintenanceList = enterpriseService.queryMaintenanceListByUnit(params);
        for (Enterprise enterprise : maintenanceList) {
            UrgentMaintenanceDto urgentMaintenanceDto = new UrgentMaintenanceDto();
            urgentMaintenanceDto.setMaintenanceDept(enterprise.getId().toString());
            BigDecimal bigDecimal = queryMaintenanceEvaluationAvg(urgentMaintenanceDto);

            MaintenanceEvaluationVo maintenanceEvaluationVo = new MaintenanceEvaluationVo();
            maintenanceEvaluationVo.setMaintenanceId(enterprise.getId().toString());
            maintenanceEvaluationVo.setMaintenanceName(enterprise.getEnterpriseName());
            maintenanceEvaluationVo.setMonthAvgScore(bigDecimal);
            maintenanceEvaluationVoList.add(maintenanceEvaluationVo);
        }
        return maintenanceEvaluationVoList.stream().sorted(Comparator.comparing(MaintenanceEvaluationVo::getMonthAvgScore).reversed()).collect(Collectors.toList());
    }

    @Override
    public int getAllUnitByDay(List<String> ids, String begin, String end) {
        return this.baseMapper.getAllUnitByDay(ids,begin,end);
    }

    @Override
    public List<ResultVo> getUnitByDay(String beginTime, String endTime, String unitId) {
        return this.baseMapper.getUnitByDay(beginTime,endTime,unitId);
    }

    @Override
    public List<ResultVo> getMonthByDate(String beginTime, String endTime, String unitId) {
        return this.baseMapper.getMonthByDate(beginTime,endTime,unitId);
    }

    @Override
    public List<ResultVo> getQuarterByDate(String beginTime, String endTime, String unitId) {
        return this.baseMapper.getQuarterByDate(beginTime,endTime,unitId);
    }

    @Override
    public List<ResultVo> getYearByDate(String beginTime, String endTime, String unitId) {
        return this.baseMapper.getYearByDate(beginTime,endTime,unitId);
    }

    @Override
    public List<ResultVo> getAllDay(String beginTime, String endTime, List<String> ids) {
        return this.baseMapper.getAllDay(beginTime,endTime,ids);
    }

    @Override
    public List<ResultVo> getAllMonth(String beginTime, String endTime, List<String> ids) {
        return this.baseMapper.getAllMonth(beginTime,endTime,ids);
    }

    @Override
    public List<ResultVo> getAllQuarter(String beginTime, String endTime, List<String> ids) {
        return this.baseMapper.getAllQuarter(beginTime,endTime,ids);
    }

    @Override
    public List<ResultVo> getAllYear(String beginTime, String endTime, List<String> ids) {
        return this.baseMapper.getAllYear(beginTime, endTime, ids);
    }

    @Override
    public List<ResultVo> getRankByDate(String beginTime, String endTime, List<String> ids) {
        return this.baseMapper.getRankByDate(beginTime, endTime, ids);
    }

    @Override
    public List<ResultVo> getTrendEcharts(String beginTime, String endTime, List<String> ids) {
        return this.baseMapper.getTrendEcharts(beginTime, endTime, ids);
    }

    @Override
    public List<MaintenanceEvaluationVo> queryMaintenanceEvaluationList(UrgentMaintenanceDto urgentMaintenanceDto) {
        Map<String, Object> params = new HashMap<>();
        params.put("sociologyDeptId", urgentMaintenanceDto.getSociologyDept());
        params.put("maintenanceDeptId", urgentMaintenanceDto.getMaintenanceDept());
        params.put("evaluationDate", urgentMaintenanceDto.getEvaluationTime());
        return this.baseMapper.queryMaintenanceEvaluationList(params);
    }

}
